package net.oschina.aibinxiao.security.ecdsa;

import org.apache.commons.codec.binary.Hex;

import java.security.*;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * @Author: AiBinXiao
 * @Description: 数字签名算法ECDSA
 * @Date: 2017/10/14 9:11
 */
public class MyECDSA {
    private static String src = "imooc security ecdsa";

    public static void main(String[] args) {
        jdkEDSA();
    }

    // JDK实现的DSA
    public static void jdkEDSA() {
        try {
            // 1.初始化密钥
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
            keyPairGenerator.initialize(256);
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            ECPublicKey ecPublicKey = (ECPublicKey) keyPair.getPublic();
            ECPrivateKey ecPrivateKey = (ECPrivateKey) keyPair.getPrivate();

            // 2.执行签名
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(ecPrivateKey.getEncoded());
            KeyFactory keyFactory = KeyFactory.getInstance("EC");
            PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
            Signature signature = Signature.getInstance("SHA1withECDSA");
            signature.initSign(privateKey);
            signature.update(src.getBytes());
            byte[] result = signature.sign();
            System.out.println("JDK ECDSA sign: " + Hex.encodeHexString(result));
            //JDK ECDSA sign: 3045022100ed0786627b4002d1f260546930d2cadf2af414115cdc7b3b132578e128a582a9022046f05c5913b5a28b3e09c2fb9a91d5da46093bb5b381dcdaf6ee1924a8d415ec

            // 3.验证签名
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(ecPublicKey.getEncoded());
            keyFactory = KeyFactory.getInstance("EC");
            PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
            signature = Signature.getInstance("SHA1withECDSA");
            signature.initVerify(publicKey);
            signature.update(src.getBytes());
            Boolean bool = signature.verify(result);
            System.out.println("JDK ECDSA verify : " + bool);
            // JDK ECDSA verify : true
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
